package net.ba.map
{

	import com.adobe.serialization.json.JSON;
	import com.google.maps.overlays.Polygon;
	import com.google.maps.overlays.PolygonOptions;
	import com.google.maps.styles.FillStyle;
	import com.google.maps.styles.StrokeStyle;
	
	import mx.core.Application;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	import net.ba.models.Model;
	import net.ba.models.TaxonName;
	import net.ba.utils.CellIdUtils;
	
	public class FlickrOverlay
	{
		public var flickrPolygons:Array = new Array();
		public var flickrColor:Number = 0x0315FF;
		public var flickrTransparency:Number = 1;
		public var flickrPolOptions:PolygonOptions = new PolygonOptions({ 
  					strokeStyle: new StrokeStyle({
  					color: flickrColor,
  					thickness: 1,
  					alpha: flickrTransparency}), 
  					fillStyle: new FillStyle({
  					color: flickrColor,
  					alpha: flickrTransparency})
							});
							
		public var flickrService:HTTPService;

		public function FlickrOverlay()
		{
			flickrService = new HTTPService();
			flickrService.resultFormat = "text";
			flickrService.url="http://pipes.yahooapis.com/pipes/pipe.run?_id=Uo7ZaIYA3BGxYDH8X0sBXw&_render=json&api_key=f8f288742b1bf1bfcf29eb5ef0ae038b";
			
		}
		
		public function getFlickrPolygonsForTaxonName(taxonName:TaxonName):void {
			flickrService.request.tags = taxonName.scientificName;
			flickrService.addEventListener(ResultEvent.RESULT,function (event:ResultEvent):void {onFlickrServiceResponse(event,taxonName);});
			flickrService.send();
		}
		
		private function onFlickrServiceResponse(event:ResultEvent,taxonName:TaxonName):void {
			var rawData:String = String(event.result);
			var jsonObj:Object = JSON.decode(rawData);
			var arr:Array = (jsonObj.value.items as Array);
			
			var cells:Array = new Array();
			for each(var item:Object in arr) {
				var c:Number = CellIdUtils.toCellId(item['geo:lat'],item['geo:long']);
				if (cells.indexOf(c)==-1) {
					cells.push(c);
				}
			}		
			
			Model.flickrPolygons = CellIdUtils.cellIdsToMultiPolygon(cells,flickrPolOptions);
			
			//Add them to the map
			for each(var pol:Polygon in Model.flickrPolygons) {
		  		Application.application.mapComp.map.addOverlay(pol); 
		  	}
			
		}		
		
		
		public function changeTransparencyToFlickr(transparency:Number):void {
		  	flickrPolOptions.strokeStyle.alpha = flickrPolOptions.fillStyle.alpha  = transparency;
		  	for each (var pol:Polygon in Model.flickrPolygons) {
		  		pol.setOptions(flickrPolOptions);
		  	}
		}
		  
		public function changeColorToFlickr(color:Number):void {
		  	flickrPolOptions.strokeStyle.color = flickrPolOptions.fillStyle.color  = color;
		  	for each (var pol:Polygon in Model.flickrPolygons) {
		  		pol.setOptions(flickrPolOptions);
		  	}
		}

		
	}
}